/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.box.redis

import com.google.inject.Provider
import cool.taomu.box.inter.IDataSource
import java.util.HashSet
import javax.inject.Inject
import javax.inject.Named
import org.slf4j.LoggerFactory
import redis.clients.jedis.JedisPoolConfig
import redis.clients.jedis.JedisSentinelPool

abstract class AbsRedisSentinelientPoolProvider implements Provider<IDataSource> {
	val LOG = LoggerFactory.getLogger(AbsRedisSentinelientPoolProvider);

	@Inject
	@Named("redis.database")
	Integer database;

	@Inject
	@Named("redis.host")
	String host;

	@Inject
	@Named("redis.port")
	Integer port;

	@Inject
	@Named("redis.password")
	String password;

	@Inject
	@Named("redis.username")
	String username;

	@Inject
	@Named("redis.timeout")
	Integer timeout;

	@Inject
	@Named("redis.master")
	String master;

	abstract def void configure(JedisPoolConfig poolConfig);

	override get() {
		var jedisPoolConfig = new JedisPoolConfig();
		this.configure(jedisPoolConfig)
		var nodeSet = new HashSet<String>();
		for (node : host.split(",")) {
			LOG.info("sentinel host:{}", #[host, port].join(":"));
			nodeSet.add(#[host, port].join(":"));
		}
		var JedisSentinelPool pool;
		if (username === null) {
			if (password === null) {
				pool = new JedisSentinelPool(master, nodeSet, jedisPoolConfig, timeout);
			} else {
				pool = new JedisSentinelPool(master, nodeSet, jedisPoolConfig, timeout, timeout, password, database);
			}
		} else if (username !== null && password !== null) {
			pool = new JedisSentinelPool(master, nodeSet, jedisPoolConfig, timeout, timeout, username, password,
				database);
		}
		return new RedisSentinelDataSource(pool);
	}

}
